package com.bsbm.common.service.impl;

import com.bsbm.common.dao.UserDao;
import com.bsbm.common.domain.Role;
import com.bsbm.common.domain.User;
import com.bsbm.common.domain.UserStatus;
//import com.bsbm.common.service.UserDetailsService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by SABIR IQBAL on 3/27/14.
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserDao userDao;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userDao.findByUserName(userName);
        if(user != null){
            String password = user.getPassword();
            boolean enabled = user.getStatus().equals(UserStatus.ACTIVE);
            boolean accountNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
            boolean credentialsNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
            boolean accountNonLocked = user.getStatus().equals(UserStatus.ACTIVE);
            Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (Role role : user.getRoles()) {
                authorities.add(new GrantedAuthorityImpl(role.getRoleName())) ;
            }
            org.springframework.security.core.userdetails.User securityUser =
                    new org.springframework.security.core.userdetails.User(userName, password, enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);

            return securityUser;
        }else {
            throw new UsernameNotFoundException("User Not Found !!");
        }

    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}
